package com.guoxin.concurrentprogramming.chapter3.synccontrol;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Administrator
 */
public class ReadWriteLockDemo {
    private static Lock lock = new ReentrantLock();
    private static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private static Lock readLock = readWriteLock.readLock();
    private static Lock writeLock = readWriteLock.writeLock();
    private static int v;

    private Object handleRead(Lock lock) throws InterruptedException {
        try {
            lock.lock();
            Thread.sleep(1000);
            return v;
        } finally {
            lock.unlock();
        }
    }

    private void handleWrite(Lock lock, int index) throws InterruptedException {
        try {
            lock.lock();
            Thread.sleep(1000);
            v = index;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        final ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();
        Runnable readRunnable = () -> {
            try {
                readWriteLockDemo.handleRead(readLock);
//                readWriteLockDemo.handleRead(lock);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        Runnable writeRunnable = () -> {
            try {
                readWriteLockDemo.handleWrite(writeLock, new Random().nextInt());
//                readWriteLockDemo.handleWrite(lock, new Random().nextInt());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        Thread[] thread = new Thread[20];

        for (int i = 0; i < 18; i++) {
            Thread t = new Thread(readRunnable);
            thread[i] = t;
            t.start();
        }

        for (int i = 18; i < 20; i++) {
            Thread t = new Thread(writeRunnable);
            thread[i] = t;
            t.start();
        }

        for(Thread t:thread){
            t.join();
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);
    }

}
